﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Mammoth.Entities;
using Mammoth.Events;
using Mammoth.Libs;
using Mammoth.Repositories;
using Mammoth.Services;

namespace Mammoth.ViewModels
{
    public class MessageCommands
    {
        public static readonly RoutedCommand RemoveCommand = new RoutedCommand();
    }

    public class MessageViewModel<T> : WPFViewModelBase where T : Entity
    {

        public string Header { get; set; }
        public IRepository<T> Repository { get; set; }
        public IList<T> MessageList { get; set; }
        public string SearchKeyword { get; set; }
        public GTalkMessageType Type { get; set; }

        public MessageViewModel(IInputElement dispatcher, IRepository<T> repo)
            : base(dispatcher)
        {
            Repository = repo;
            Dispatcher.AddHandler(RoutedEvents.MessageDataChangeEvent, new RoutedEventHandler<MessageDataChangeEventArgs>(OnMessageDataChangeHandler));
            GetMessageAsync();
        }

        private void OnMessageDataChangeHandler(object sender, MessageDataChangeEventArgs e)
        {
            GetMessageAsync();
        }

        ~MessageViewModel()
        {
            Repository.Dispose();
            Dispatcher.RemoveHandler(RoutedEvents.MessageDataChangeEvent, new RoutedEventHandler<MessageDataChangeEventArgs>(OnMessageDataChangeHandler));
        }

        public void GetMessageAsync()
        {
            Task.Factory.StartNew(GetMessageList);
        }

        public void GetMessageList()
        {
            try
            {
                MessageList = new ObservableCollection<T>(Repository.Get(null, 0, 20));
            }
            catch (Exception)
            {
                Dispatcher.RaiseErrorEvent("Gagal meload pesan dari database");
            }
        }

        public void RemoveHandler(object sender, ExecutedRoutedEventArgs e)
        {
            var entity = (T)e.Parameter;
            var msg = string.Format("Anda yakin akan menghapus pesan dari pesan?");
            var me = new MessageBoxEventArgs(msg, "Konfirmasi", MessageBoxButton.YesNo);
            RaiseEvent(me);
            if (me.Result == MessageBoxResult.Yes)
            {
                try
                {
                    Repository.Delete(entity);
                    MessageList.Remove(entity);
                }
                catch (Exception)
                {
                    Dispatcher.RaiseErrorEvent("Gagal menghapus data ke database");
                }
            }
                
        }
    }
}
